package com.cfpl.security;

import cn.hutool.json.JSONUtil;
import com.cfpl.project_common.result.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: LYP
 * @Date: 2023/10/12 - 11:22
 * @Description: com.cfpl.admin_service.security
 * @version: 1.0
 */
@Slf4j
@Component
public class LoginFairedHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("******Security登陆失败处理器********");
        response.setContentType("text/json;charset=utf-8");
        BaseResult<Object> result ;


//        if (exception instanceof AccountExpiredException) {
//            //账号过期
//            result = new BaseResult<>(403, "权限不足", null);
//        } else if (exception instanceof BadCredentialsException) {
//            //密码错误
//            result = new BaseResult<>(403, "权限不足", null);
//        } else if (exception instanceof CredentialsExpiredException) {
//            //密码过期
//            result = new BaseResult<>(403, "权限不足", null);
//        }else if (exception instanceof InternalAuthenticationServiceException) {
//            //用户不存在
//            result = new BaseResult<>(403, "权限不足", null);
//        }else{
//            //其他错误
//            result = new BaseResult<>(403, "权限不足", null);
//        }
//        if (exception instanceof DisabledException) {
//            //账号不可用
//            result = new BaseResult<>(101, "账号不可用", null);
//            response.getWriter().write(JSONUtil.toJsonStr(result));
//        } else
        if (exception instanceof LockedException) {
            //账号锁定
            result = new BaseResult<>(102, "账号锁定", null);
            response.getWriter().write(JSONUtil.toJsonStr(result));
            return;
        }

        result = new BaseResult<>(402, "用户名或密码错误", null);
        response.getWriter().write(JSONUtil.toJsonStr(result));

    }
}
